package com.learning.javaweb_servlet_jdbc;

import java.sql.*;

public class JDBC_Teacher_Create {
    //设置基础数据，链接数据库
    static final String URL = "jdbc:mysql://localhost:3306/jdbc_demo?useSSL=false&serverTimezone=GMT&characterEncoding=UTF-8";
    static final String USER = "root";
    static final String PASSWORD = "WQ9ABCAT";

    //插入语句
    static final String SQL = "INSERT INTO teacher (id,name,course,birthday) VALUES (?,?,?,?)";

    public static void main(String[] args) {
        // 加载mysql驱动
        try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);) {
            //关闭事务自动提交
            conn.setAutoCommit(false);
            // 创建Statement对象
            try (PreparedStatement ps = conn.prepareStatement(SQL);) {
                // 设置参数
                ps.setInt(1,4);
                ps.setString(2, "z");
                ps.setString(3, "数学");

                Date sqlDate = Date.valueOf("2020-07-10");
                ps.setDate(4, sqlDate);
                // 执行插入
                ps.executeUpdate();
                conn.commit();
            } catch (SQLException e) {
                conn.rollback();
                e.printStackTrace();
            } finally {
                conn.setAutoCommit(true);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}